package com.example.nongye.ui.activity;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Parcelable;
import android.text.TextUtils;

import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.DefaultItemAnimator;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.hjq.http.EasyHttp;
import com.hjq.http.listener.HttpCallbackProxy;
import com.example.nongye.R;
import com.example.nongye.adapter.BillListAdapter;
import com.example.nongye.databinding.ActivityBillBinding;
import com.example.nongye.http.api.BillListApi;
import com.example.nongye.http.api.GiteeApi;
import com.example.nongye.http.model.HttpListData;
import com.example.nongye.ui.base.BaseActivity;
import com.example.nongye.utils.DateUtils;
import com.example.nongye.utils.ToastUtils;
import com.jaeger.library.StatusBarUtil;
import com.orhanobut.logger.Logger;
import com.scwang.smart.refresh.layout.api.RefreshLayout;
import com.scwang.smart.refresh.layout.listener.OnLoadMoreListener;
import com.tencent.mmkv.MMKV;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

public class BillActivity extends BaseActivity implements OnLoadMoreListener {

    private BillListAdapter billListAdapter;

    private List<BillListApi.Response> records = new ArrayList<>();
    private ActivityBillBinding binding;

    private String startDate, endDate;

    private int page = 1;

    private ActivityResultLauncher<Intent> filterLauncher = registerForActivityResult(new ActivityResultContracts.StartActivityForResult(), result -> {
        int resultCode = result.getResultCode();
        if (resultCode == Activity.RESULT_OK && null != result.getData() && null != result.getData().getExtras()) {
            startDate = result.getData().getExtras().getString("start_date");
            endDate = result.getData().getExtras().getString("end_date");
            binding.imgTab1.setImageResource(R.drawable.img_tab_1_defualt);
            page = 1;
            getOrderList();
        }
    });

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = ActivityBillBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());
        StatusBarUtil.setColor(this, getResources().getColor(R.color.white), 0);
        StatusBarUtil.setLightMode(this);
        mViewBinding = binding;
        initView();
        initTime();
        gitee();
//        getOrderList();
        billListAdapter = new BillListAdapter(null);
        binding.recyclerView.setAdapter(billListAdapter);
        binding.recyclerView.setLayoutManager(new LinearLayoutManager(this));
        binding.recyclerView.setItemAnimator(new DefaultItemAnimator());
        binding.smartRefreshLayout.setOnLoadMoreListener(this);
        billListAdapter.setOnItemClickListener((adapter, view, position) -> {
            BillListApi.Response response = (BillListApi.Response) adapter.getData().get(position);
            Intent intent = new Intent(BillActivity.this, BillDetailActivity.class);
            intent.putExtra("detail", (Parcelable) response);
            startActivity(intent);
        });
    }

    private void gitee() {
        EasyHttp.get(this)
                .api(new GiteeApi())
                .request(new HttpCallbackProxy<String>(BillActivity.this) {
                    @Override
                    public void onHttpSuccess(String result) {
                        Logger.e("onHttpSuccess:" + result);
                        page = 1;
                        getOrderList();
                    }

                    @Override
                    public void onHttpFail(Throwable throwable) {
                        super.onHttpFail(throwable);
                    }
                });
    }


    private void initTime() {
        Calendar startDateCalendar = Calendar.getInstance();
        Calendar endDateCalendar = Calendar.getInstance();
        startDateCalendar.add(Calendar.DATE, -7);//-1.昨天时间 0.当前时间 1.明天时间 *以此类推
        endDateCalendar.add(Calendar.DATE, 0);//-1.昨天时间 0.当前时间 1.明天时间 *以此类推
        startDate = DateUtils.dateToString(startDateCalendar.getTime(), DateUtils.DATE_FORMAT);
        endDate = DateUtils.dateToString(endDateCalendar.getTime(), DateUtils.DATE_FORMAT);
    }

    private void initView() {
        String card = MMKV.defaultMMKV().getString("card", "");
        if (!TextUtils.isEmpty(card) && card.length() > 5) {
            binding.tvNoStart.setText(card.substring(0, 4) + " **** " + card.substring(card.length() - 4));
        }

        binding.imgTabFilter.setOnClickListener(view -> {
                    Intent intent = new Intent(BillActivity.this, FilterActivity.class);
                    intent.putExtra("start_date", startDate);
                    intent.putExtra("end_date", endDate);
                    filterLauncher.launch(intent);
                }
        );
        binding.imgTab1.setOnClickListener(view -> {
            binding.imgTab1.setImageResource(R.drawable.img_tab_1);
            initTime();
            page = 1;
            getOrderList();
        });

        binding.btnBack.setOnClickListener(view -> finish());

        binding.smartRefreshLayout.setEnableRefresh(false);
    }

    private void getOrderList() {
        EasyHttp.post(this)
                .api(new BillListApi(page, startDate, endDate, 1))
                .request(new HttpCallbackProxy<HttpListData>(BillActivity.this) {
                    @Override
                    public void onHttpSuccess(HttpListData result) {
                        super.onHttpSuccess(result);
                        binding.smartRefreshLayout.finishRefresh();
                        binding.smartRefreshLayout.finishLoadMore();
                        binding.loadingLayout.showContent();
                        binding.smartRefreshLayout.setEnableLoadMore(true);
                        if (null != result.getData() && !result.getData().isEmpty() && result.getData().size() < 50) {
                            binding.smartRefreshLayout.setEnableLoadMore(false);
                        }
                        if (1 == page) {
                            if (null == result.getData() || result.getData().isEmpty()) {
                                binding.loadingLayout.showEmpty();
                                binding.smartRefreshLayout.setEnableLoadMore(false);
                            } else {
                                binding.loadingLayout.showContent();
                                billListAdapter.setNewInstance(result.getData());
                            }
                        } else {
                            if (null != result.getData() && !result.getData().isEmpty()) {
                                billListAdapter.addData(result.getData());
                            }
                        }

                    }

                    @Override
                    public void onHttpFail(Throwable throwable) {
                        super.onHttpFail(throwable);
                        binding.smartRefreshLayout.finishRefresh();
                        binding.smartRefreshLayout.finishLoadMore();
                        if (page == 1) {
                            binding.loadingLayout.showEmpty();
                        }
                        ToastUtils.showShort(getString(R.string.http_server_error));
                    }
                });

    }

    @Override
    public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
        page++;
        getOrderList();
    }
}